import {globalConfig} from './config.js'

async function generate(path, data, callback, endCallback) {
    // const url = "http://43.139.165.170:7012/api/" + path;
    const url = globalConfig.baseUrl + "api/" + path;
    const response = await fetch(url, {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
            "Content-Type": "application/json"
        }
    })
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    while (true) {
        const { done, value } = await reader.read();
        if (done) {
            endCallback()
            break
        }
        let decodedText = decoder.decode(value);
        decodedText = JSON.parse(decodedText)
        if(decodedText.status === 'success'){
            console.log(decodedText.text)
            callback(decodedText.text)
        }else if(decodedText.status === 'end'){
            endCallback()
            break
        }else if(decodedText.status === 'error'){
            ElMessage({message: decodedText.msg,type: 'error',})
            endCallback()
            break
        }
        // const msgs = decodedText.split('\0')
        // msgs.pop()
        // for(let i = 0; i < msgs.length; i++){
        //     const mess = JSON.parse(msgs[i])
        //     if(mess.status === 'success'){
        //         console.log(mess.text)
        //         callback(mess.text)
        //     }else if(mess.status === 'end'){
        //         endCallback()
        //         break
        //     }else if(mess.status === 'error'){
        //         ElMessage({message: mess.msg,type: 'error',})
        //         endCallback()
        //         break
        //     }
        // }
    }
}
export {generate}
